package demo.admin.filter;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTException;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import demo.admin.common.BaseResult;
import demo.admin.common.ResultCode;
import demo.admin.config.GlobalConfig;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * JWT登录验证拦截器
 */
@Order(1)
@WebFilter(filterName = "tokenFilter",urlPatterns = { "/role/*", "/example/*"})
public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException{

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String token = request.getHeader("Authorization");
        //校验token
        if(StrUtil.isBlank(token) || !JWTUtil.verify(token, GlobalConfig.SECRET_KEY.getBytes())){
            //校验失败
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSONUtil.toJsonStr(BaseResult.error(ResultCode.FAILED_NOT_LOGIN)));
            return;
        }

        //校验失效时间
        try {
            JWTValidator.of(token).validateDate(DateUtil.date());
        } catch (ValidateException exception) {
            //token过期
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSONUtil.toJsonStr(BaseResult.error(ResultCode.FAILED_TOKEN_EXPIRE)));
            return;
        }

        //通过校验
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

}